<script setup>
import { onMounted, ref } from "vue";
import { Edit, Delete, Search } from "@element-plus/icons-vue";
import EditTakeoutDialog from "./EditTakeoutDialog.vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

onMounted(() => {
  initData();
});

// 门店选项
const storeOptions = ref([
  { value: "", label: "全部城市" },
  { value: "北京", label: "北京" },
  { value: "上海", label: "上海" },
  { value: "广州", label: "广州" },
  { value: "深圳", label: "深圳" },
]);

// 外卖状态选项
const takeoutStatusOptions = ref([
  { value: "", label: "全部状态" },
  { value: 1, label: "开启外卖" },
  { value: 0, label: "关闭外卖" },
]);

// 筛选条件
const filterForm = ref({
  city: "",
  allowTakeOut: "",
});

// 表格数据
const tableData = ref([]);
const initData = () => {
  if (filterForm.value.city !== "" || filterForm.value.allowDineIn !== "") {
    axios
      .post(
        `/takeOutSetting/getInfo/${pageNum.value}/${pageSize.value}`,
        filterForm.value
      )
      .then((res) => {
        tableData.value = res.data.obj.data;
        totalPage.value = res.data.obj.total;
      });
  } else {
    axios
      .post(`/takeOutSetting/getInfo/${pageNum.value}/${pageSize.value}`)
      .then((res) => {
        tableData.value = res.data.obj.data;
        totalPage.value = res.data.obj.total;
      });
  }
};

// 多选
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 查询方法
const handleQuery = () => {
  pageNum.value = 1; // 重置到第一页
  initData();
};

// 批量删除方法
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  const storeNames = multipleSelection.value
    .map((item) => item.storeName)
    .join("、");
  const ids = multipleSelection.value.map((item) => item.id);

  ElMessageBox.confirm(
    `确认删除选中的【${storeNames}】等${multipleSelection.value.length}条外卖设置吗？`,
    "批量删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      axios
        .post("/takeOutSetting/batchDelete", ids)
        .then((res) => {
          if (res.data) {
            ElMessage.success(
              `成功删除${multipleSelection.value.length}条记录`
            );
            initData();
            multipleSelection.value = []; // 清空选择
          } else {
            ElMessage.error(res.data.message || "批量删除失败");
          }
        })
        .catch((err) => {
          ElMessage.error("批量删除请求失败");
          console.error(err);
        });
    })
    .catch(() => {
      ElMessage.info("已取消批量删除");
    });
};

// 删除方法
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除门店【${row.storeName}】的外卖设置吗？`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      axios
        .get(`/takeOutSetting/delete/${row.id}`)
        .then((res) => {
          if (res.data) {
            ElMessage.success("删除成功");
            initData();
          } else {
            ElMessage.error(res.data.message || "删除失败");
          }
        })
        .catch((err) => {
          ElMessage.error("删除请求失败");
          console.error(err);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 编辑功能
const showEditDialog = ref(false);
const currentRow = ref({});

const handleEdit = (row) => {
  currentRow.value = { ...row };
  showEditDialog.value = true;
};

const handleConfirmEdit = (formData) => {
  console.log("确认编辑:", formData);
  axios
    .post("/takeOutSetting/update", formData)
    .then((res) => {
      if (res.data === true) {
        ElMessage.success("修改成功");
        initData();
      } else {
        ElMessage.error(res.data.message || "修改失败");
      }
      showEditDialog.value = false;
    })
    .catch((err) => {
      ElMessage.error("请求失败");
      console.error(err);
    });
};

// 分页
const pageNum = ref(1);
const pageSize = ref(10);
const totalPage = ref(0);

const handleSizeChange = (val) => {
  pageSize.value = val;
  initData();
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
  initData();
};
</script>

<template>
  <div class="takeout-container">
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="城市选择">
          <el-select
            v-model="filterForm.city"
            placeholder="全部城市"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in storeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="外卖状态">
          <el-select
            v-model="filterForm.allowTakeOut"
            placeholder="全部状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in takeoutStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="table-header">
        <el-button
          type="danger"
          :icon="Delete"
          :disabled="multipleSelection.length === 0"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55px" />
        <el-table-column prop="storeName" label="门店" width="auto" />
        <el-table-column prop="allowTakeOut" label="外卖状态" width="auto">
          <template #default="scope">
            <el-tag :type="scope.row.allowTakeOut ? 'success' : 'danger'">
              {{ scope.row.allowTakeOut ? "开启" : "关闭" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              :icon="Edit"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-block">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <EditTakeoutDialog
      v-if="showEditDialog"
      :row-data="currentRow"
      @close="showEditDialog = false"
      @confirm="handleConfirmEdit"
    />
  </div>
</template>

<style lang="scss" scoped>
.takeout-container {
  padding: 20px;
  background-color: #f5f7fa;

  .filter-container {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .filter-form {
      display: flex;
      align-items: center;
    }
  }

  .table-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .table-header {
      margin-bottom: 15px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .pagination-block {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
